import json
import logging
import random
import re
import time

import expire as expire
import requests
from django.http import JsonResponse
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service

from App.get_cookie import GetCookie
from Browser.xhs_cookie import *
from FS_RPA import settings
from .upimg_cos import upimg

# 配置日志
logger = logging.getLogger(__name__)

cookie_gen = GetCookie()
generator = cookie_gen.get_next_cookie()
cookies = next(generator)


headers = {
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
}


def browser_process(**kwargs):
    screenshot_path = kwargs.get('url')
    table_id1 = kwargs.get('table_id1', 0)
    table_id2 = kwargs.get('table_id2', 0)
    table_id3 = kwargs.get('table_id3', 0)
    table_id4 = kwargs.get('table_id4', 0)

    if table_id2 == 0 and table_id1 == 0:
        # 初始化返回数据
        result = {
            '点赞量': '',
            '收藏量': '',
            '评论量': '',
            '分享': ''
        }

        try:
            response = requests.get(
                screenshot_path, headers=headers,
                cookies=cookies)
            time.sleep(random.uniform(5,10))
            response.raise_for_status()

            # 使用正则表达式提取互动信息
            pattern = r'"interactInfo":\s*\{[^}]+\}'
            match = re.search(pattern,
                              response.text)

            if match:
                interact_str = match.group()
                full_json_str = "{" + interact_str + "}"
                data = json.loads(full_json_str)
                interact_info = data.get(
                    "interactInfo", {})

                # 提取数据
                result[
                    '点赞量'] = interact_info.get(
                    "likedCount", "")
                result[
                    '收藏量'] = interact_info.get(
                    "collectedCount", "")
                result[
                    '评论量'] = interact_info.get(
                    "commentCount", "")
                result[
                    '分享'] = interact_info.get(
                    "shareCount", "")
                logger.info(
                    f"成功提取数据: {result}")
            else:
                logger.warning("未找到互动信息")

            return result

        except Exception as e:
            logger.error(
                f"抓取数据失败: {str(e)}")
            return None

    result = {
        '发布截图': '',
        '点赞量': '',
        '收藏量': '',
        '评论量': '',
        '分享': ''
    }

    response = requests.get(screenshot_path,
                            headers=headers,
                            cookies=cookies)
    time.sleep(random.uniform(5, 10))
    pattern = r'"interactInfo":\s*\{[^}]+\}'
    try:
        match = re.search(pattern, response.text)
        if match:
            interact_str = match.group()
            logging.info("interactInfo解析成功")
        else:
            interact_str = ""
            logging.error(
                f"解析错误：未在响应中找到interactInfo，响应内容：{response.text[:500]}")

        full_json_str = "{" + interact_str + "}"
        data = json.loads(full_json_str)
        interact_info = data.get("interactInfo",
                                 {})

        liked_count = interact_info.get(
            "likedCount", "") if isinstance(
            interact_info, dict) else ""
        collected_count = interact_info.get(
            "collectedCount", "") if isinstance(
            interact_info, dict) else ""
        comment_count = interact_info.get(
            "commentCount", "") if isinstance(
            interact_info, dict) else ""
        share_count = interact_info.get(
            "shareCount", "") if isinstance(
            interact_info, dict) else ""
    except json.JSONDecodeError:
        logger.error("JSON 解析失败！！！！！")

    # 配置Chrome浏览器
    options = Options()
    options.add_argument(
        'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36'
    )
    options.add_argument('--disable-gpu')
    options.add_argument(
        '--window-size=1920,1080')
    options.add_argument(
        '--disable-dev-shm-usage')
    options.add_argument('--headless=new')  # 无头模式

    chromedriver_path = r'chromedriver.exe'

    browser = None
    try:
        service = Service(
            executable_path=chromedriver_path)
        browser = webdriver.Chrome(
            service=service, options=options)
        logger.error("浏览器启动成功")

        browser.get(screenshot_path)

        os.makedirs(settings.MEDIA_ROOT,
                    exist_ok=True)
        screenshot_name = '1.png'
        image_url = os.path.join(
            settings.MEDIA_ROOT, screenshot_name)

        save_success = browser.save_screenshot(
            image_url)
        if not save_success or not os.path.exists(image_url):
            raise Exception("截图保存失败")

        image = upimg(image_url)

        if os.path.exists(image_url):
            os.remove(image_url)

    except Exception as e:
        logger.error(f"截图过程出错：{str(e)}")
        return JsonResponse({
            'code': 500,
            'message': f'截图生成失败：{str(e)}'
        })
    finally:
        if browser:
            browser.quit()

    result['发布截图'] = {
        'link': image,
        'text': ''
    }
    result['点赞量'] = liked_count
    result['收藏量'] = collected_count
    result['评论量'] = comment_count
    result['分享'] = share_count

    return result
